package com.wzx.boot.autoconfig.tomcat;

import org.apache.catalina.Context;
import org.apache.catalina.LifecycleException;
import org.apache.catalina.startup.Tomcat;
import org.springframework.context.annotation.*;
import org.springframework.web.servlet.DispatcherServlet;

import java.io.File;
import java.util.HashSet;

@ComponentScan
@Configuration
@Scope(proxyMode = ScopedProxyMode.NO)
public class TomcatAutoConfiguration {

    @Bean
    public Tomcat tomcat(ServerProperties properties, DispatcherServlet dispatcherServlet) throws LifecycleException {
        Tomcat tomcat = new Tomcat();
        tomcat.setPort(properties.getPort());
        File docBase = new File(System.getProperty("java.io.tmpdir"));
        Context context = tomcat.addContext("", docBase.getAbsolutePath());
        WzxServletInitializer wzxServletInitializer = new WzxServletInitializer(dispatcherServlet);
        context.addServletContainerInitializer(wzxServletInitializer, new HashSet<>());
        tomcat.start();
        Thread thread = new Thread(() -> {
            tomcat.getServer().await();
        });
        thread.setContextClassLoader(getClass().getClassLoader());
        thread.setDaemon(false);
        thread.start();
        return tomcat;
    }
}
